<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2018 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +---------------------------------------------------------------------
// | Author: 小夏 < 449134904@qq.com>
// +----------------------------------------------------------------------
namespace cmf\controller;

use think\Db;

class AdminBaseController extends BaseController
{

    public function _initialize()
    {
        // 监听admin_init
        hook('admin_init');
        parent::_initialize();
        $session_admin_id = session('ADMIN_ID');
        if (!empty($session_admin_id)) {
            // 分析用户属性.后台用户才能登录管理后台
            $user = Db::name('user')->where(['id' => $session_admin_id])->where(['user_type' => 1])->find();

            // 非超级账户检测,权限检测
            if (!$this->checkAccess($session_admin_id)) {
                $this->error("您没有访问权限！");
            }
            $this->assign("admin", $user);
        } else {
            // 需要认证下才能登录
            // 强制跳转登录页
//            $url= url('index/public/login', '', false, true);
            $url= url('/admin/#index/public/login');
            if ($this->request->isPost()) {
                $this->error("您还没有登录！", $url);
            } else {
                if(IS_SWOOLE){
                    return $this->location($url);
                }else{
                    header("Location:" . $url);
                    exit();
                }   
            }
        }
    }

    /**
     * view公共初始内容
     */
    public function _initializeView()
    {
        $cmfAdminThemePath = config('cmf_admin_theme_path');
        $cmfAdminDefaultTheme = cmf_get_current_admin_theme();

        $themePath = "{$cmfAdminThemePath}{$cmfAdminDefaultTheme}";

        $root = cmf_get_root();
        $app_root=get_app_root();

        // 使cdn设置生效
        $cdnSettings = cmf_get_option('cdn_settings');
        if (empty($cdnSettings['cdn_static_root'])) {
            $viewReplaceStr = [
                '__ROOT__' => $app_root,
                '__TMPL__' => "{$root}/{$themePath}",
                '__STATIC__' => "{$root}/static",
                '__WEB_ROOT__' => $root
            ];
        } else {
            $cdnStaticRoot = rtrim($cdnSettings['cdn_static_root'], '/');
            $viewReplaceStr = [
                '__ROOT__' => $root,
                '__TMPL__' => "{$cdnStaticRoot}/{$themePath}",
                '__STATIC__' => "{$cdnStaticRoot}/static",
                '__WEB_ROOT__' => $cdnStaticRoot
            ];
        }

        $viewReplaceStr = array_merge(config('view_replace_str'), $viewReplaceStr);
        // 根据当前APP来定位使用的模板
        config('template.view_base', "$themePath/");
        if (IS_SWOOLE) {
            // 为了区分模板载入路径.不同端进来后,会存在定位模板的问题.
            session('template.view_base_'.APP_NAME, "$themePath/");
        }
        config('view_replace_str', $viewReplaceStr);
    }

    /**
     * 初始化后台菜单
     */
    public function initMenu()
    {
    }

    /**
     *  检查后台用户访问权限
     * @param int $userId 后台用户id
     * @return boolean 检查通过返回true
     */
    private function checkAccess($userId)
    {
        // 如果用户id是1，则无需判断
        if ($userId == 1) {
            return true;
        }

        $module     = $this->request->module();
        $controller = $this->request->controller();
        $action     = $this->request->action();
        $rule       = $module . $controller . $action;

        $notRequire = ["adminIndexindex", "adminMainindex"];
        if (!in_array($rule, $notRequire)) {
            return cmf_auth_check($userId);
        } else {
            return true;
        }
    }


    /**
     * 加载模板输出
     * @access protected
     * @param string $template 模板文件名
     * @param array $vars 模板输出变量
     * @param array $replace 模板替换
     * @param array $config 模板参数
     * @return mixed
     */
    protected function fetch($template = '', $vars = [], $replace = [], $config = [])
    {
        $template = $this->parseTemplate($template);
//        var_dump($template);exit;
        return parent::fetch($template, $vars, $replace, $config);
    }

    /**
     * 自动定位模板文件
     * @access private
     * @param string $template 模板文件规则
     * @return string
     */
    private function parseTemplate($template)
    {
        // 分析模板文件规则
        $request = $this->request;
        // 获取视图根目录
        if (strpos($template, '@')) {
            // 跨模块调用
            list($module, $template) = explode('@', $template);
        }

        if (IS_SWOOLE) {
            // 利用访问时间判断是调用哪个模板
//            if (isset($_SESSION['think']['template']["home_time"])) {
//                $home_time = $_SESSION['think']['template']["home_time"];
//            } else {
//                $home_time = 0;
//            }
//            if (isset($_SESSION['think']['template']["admin_time"])) {
//                $admin_time = $_SESSION['think']['template']["admin_time"];
//            } else {
//                $admin_time = 0;
//            }
/*
            if ($home_time != 0 || $admin_time != 0) {
                if ($admin_time > $home_time) {
                    config('template.view_base', $_SESSION['think']['template']["view_base_admin"]);
                } else {

                    config('template.view_base', $_SESSION['think']['template']["view_base"]);
                }
            }
			*/
        }



        $viewBase = config('template.view_base');

        if ($viewBase) {
            // 基础视图目录
            $module = isset($module) ? $module : $request->module();
            $path   = $viewBase . ($module ? $module . DS : '');
        } else {
            $path = isset($module) ? APP_PATH . $module . DS . 'view' . DS : config('template.view_path');
        }

        $depr = config('template.view_depr');
        if (0 !== strpos($template, '/')) {
            $template   = str_replace(['/', ':'], $depr, $template);
            $controller = cmf_parse_name($request->controller());
            if ($controller) {
                if ('' == $template) {
                    // 如果模板文件名为空 按照默认规则定位
                    $template = str_replace('.', DS, $controller) . $depr . $request->action();
                } elseif (false === strpos($template, $depr)) {
                    $template = str_replace('.', DS, $controller) . $depr . $template;
                }
            }
        } else {
            $template = str_replace(['/', ':'], $depr, substr($template, 1));
        }
//        var_dump($path,$template);exit;
        return $path . ltrim($template, '/') . '.' . ltrim(config('template.view_suffix'), '.');
    }

}